package com.tencent.qf.mybatis.config;

import com.tencent.qf.common.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MysqlSSHRunner implements ApplicationRunner, ApplicationListener<ContextClosedEvent> {

    @Autowired
    private MysqlSSHProperties mysqlSSHProperties;

    private SSHConnection sshConnection;

    @Override
    public void run(ApplicationArguments args) {
        try {

            ApplicationContext applicationContext = SpringContextUtils.getApplicationContext();
            String env = applicationContext.getEnvironment().getActiveProfiles()[0];
            if ("local".equals(env) || "dev".equals(env)) {
                // local环境，数据库走ssh隧道连89库
                log.info("ApplicationRunner开始：local环境，走ssh数据库隧道连89库");
                sshConnection = new SSHConnection(mysqlSSHProperties);
            }
        } catch (Throwable e) {
            log.error("mysql 数据库ssh隧道失败：", e);
        }
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
        if (sshConnection != null) {
            log.info("contextClosedEvent: 关闭ssh数据库隧道");
            sshConnection.closeSSH();
        }
    }
}